const netMessage = {
  "250": "微信临时code失效"
}

var Fly = require("./wx.js") //wx.js为您下载的源码文件
var fly = new Fly; //创建fly实例
var tokenFly = new Fly();
import util from './index.js';
const regeneratorRuntime = util.regeneratorRuntime
import siteInfo from '../siteinfo.js';
const prefix = siteInfo.prefix

//添加finally方法
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => {
      throw reason
    })
  );
};

//定义构造请求地址函数
const isWq = false; //是否构造微擎地址
const formatUrl = function (url) {
  if (isWq) {
    let model_name = "longbing_shequpintuan";
    url = `${siteInfo.siteroot}?i=${siteInfo.uniacid}&t=${siteInfo.multiid}&v=${siteInfo.version}&from=wxapp&c=entry&a=wxapp&do=api&m=${model_name}&s=${url}`;
    return url;
  } else {
    url = `${siteInfo.siteroot}${url}`;
    return url
  }
}
//阿里云地址转为本地域名的
const formatImageUrl = function (url) {
  // console.log(url)
  if (url.indexOf(siteInfo.siteroot) > -1) {
    return url
  } else {
    return `${formatUrl("api/Common/getImage")}&path=${url}`
  }
}

//登录
const login = async function () {
  let url = "/api/home/user/loginBycode"
  url = formatUrl(url)
  let token;
  try {
    let {
      code
    } = await prefix.pro.login();
    let d = await tokenFly.post(url, {
      code: code
    });
    if (d.data.errNum != 200) {
      throw {
        status: d.data.errNum,
        message: d.data.errMsg
      };
    }
    //登录成功
    let res = d.data.result;
    return res;
  } catch (e) {
    console.log('登录失败报错', e)
    //登录失败报错
    util.hideAll();
    util.networkError(netMessage[e.status] || e.message, e.status);
    return await Promise.reject(e);
  }
}

//设置超时
fly.config.timeout = 20000;


//给所有请求添加自定义header
fly.config.headers = tokenFly.config.headers = {
  "content-type": "application/x-www-form-urlencoded"
}

//添加请求拦截器
fly.interceptors.request.use((request) => {
  //添加验证token
  let token = prefix.getStorageSync('token');

  if (!token) {
    fly.lock()
    return login()
      .then((res) => {
        let {
          token
        } = res;
        prefix.setStorageSync("token", token); //token
      }).finally(() => {
        fly.unlock();
      }).then(() => {
        return fly.request(request);
      })
  } else {
    request.headers["token"] = token;
  }
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    //只将请求结果的data字段返回
    if (response.data.errNum == 401) {
      fly.lock()
      return login()
        .then((res) => {
          let {
            token,id
          } = res;
          //保存token和将token动态加入header
          response.request.headers["token"] = token;
          prefix.setStorageSync("token", token); //保存uid
          prefix.setStorageSync("uid", id); //保存uid
        }).finally(() => {
          //解锁后，会继续发起请求队列中的任务
          console.log("解锁")
          fly.unlock();
        }).then(() => {
          console.log("重新发起请求")
          //只有最终返回request对象时，原来的请求才会继续
          return fly.request(response.request);
        })
    } else {
      return response.data;
    }
  },
  (e) => {
    //发生网络错误后会走到这里
    util.hideAll()
    console.log('响应拦截器', e)
    // 服务器错误 报500
    // if (e.status == 500) {
    //   return
    // }
    util.networkError(netMessage[e.status] || e.message, e.status);
  }
)

// 定义上传,picture--代表图片 audio--音频 video--视频,默认picture
const uploadFile = async (url, {
  name = "file",
  filePath,
  formData = {
    type: "picture"
  }
} = {}) => {
  console.log('上传开始')
  console.log(filePath)
  url = formatUrl(url)
  try {
    let res = await wx.pro.uploadFile({
      url,
      filePath,
      name,
      formData
    })
    console.log('上传后')
    console.log(res)
    //网络请求错误
    if (res.statusCode != 200) {
      throw {
        message: "上传失败,请检查网络后重试!",
        status: res.statusCode
      };
    }
    //服务器提示错误
    let data = JSON.parse(res.data)

    if (data.errNum != 200) {
      throw {
        message: "上传失败,请检查上传配置后重试!",
        status: res.statusCode
      };
    }
    return data.result
  } catch (e) {
    util.hideAll()
    util.networkError(netMessage[e.status] || e.message);
    return await Promise.reject(e);
  }
}

//统一处理请求
const req = {
  async post(url, param) {
    //构造请求地址
    url = formatUrl(url);
    try {
      let d = await fly.post(url, param)

      //报错统一处理
      if (d.errNum != 200) throw d
      return d.result

    } catch (d) {
      util.hideAll()

      util.showModal(d.errMsg + '')
      return await Promise.reject(d);
    }
  },
  async get(url, param) {
    //构造请求地址
    url = formatUrl(url);
    try {
      let d = await fly.get(url, param)

      if (d.errNum != 200) throw d
      return d.result

    } catch (d) {
      util.hideAll()
      util.showModal(d.errMsg + '')

      return await Promise.reject(d);
    }
  },
}
export {
  fly,
  req,
  uploadFile,
  formatImageUrl
}